package com.white.hot.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.white.hot.utils.TextUtils;

@Controller
@EnableWebMvc
@RequestMapping("/uploadFiles")
public class ResourceAccessController extends BaseController
{
	@RequestMapping(value="/HeadImg/**",produces = "image/*")
	public void uploadFile(HttpServletRequest req, HttpServletResponse response)
	{
		StringBuffer sb = req.getRequestURL();
		String relativePath = "uploadFiles/HeadImg/";
		int start = sb.indexOf(relativePath);
		String absPath = sb.substring(start, sb.length());
		String imgRealPath = req.getSession().getServletContext().getRealPath(absPath);
		if(!TextUtils.isEmpty(imgRealPath))
		{
			File f = new File(imgRealPath);
			if(f.exists())
			{
				write2Client(f, response);
			}
		}
	}

	private void write2Client(File f, HttpServletResponse response)
	{
		OutputStream targetOs = null;
		BufferedOutputStream targetBos = null;
		BufferedInputStream sourceBis = null;
		try
		{
			targetOs = response.getOutputStream();
			if(targetOs != null)
			{
				sourceBis = new BufferedInputStream(new FileInputStream(f));
				targetBos = new BufferedOutputStream(targetOs);
				int len = 0;
				byte[] buffer = new byte[1024];
				while((len = sourceBis.read(buffer)) > 0)
				{
					targetBos.write(buffer, 0, len);
				}
				targetBos.flush();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}finally
		{			
			try
			{
				if(targetBos != null)
				{
					targetBos.close();
				}
				if(sourceBis != null)
				{
					sourceBis.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}		
	}
}
